package top.igotcha.chapter.chapter7;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Gotcha
 * @date 2021/3/12
 * @describe 固定大小线程池
 */
@Slf4j(topic = "FixedThreadPoolTest")
public class FixedThreadPoolTest {
    public static void main(String[] args) {
        // 自定义线程工厂
        ThreadFactory factory = new ThreadFactory() {
            AtomicInteger atomicInteger = new AtomicInteger(1);

            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, "gotchaThread_" + atomicInteger.getAndIncrement());
            }
        };

        // 创建核心线程数量为2的线程池
        // 通过 ThreadFactory可以给线程添加名字
        ExecutorService pool = Executors.newFixedThreadPool(2,factory);

        pool.execute(()->log.debug("1"));
        pool.execute(()->log.debug("2"));
        pool.execute(()->log.debug("3"));
    }
}
